<template>
  <div class="new-render-wrapper">
    <!-- <el-button type="text" icon="el-icon-printer" class="new-print-btn avue-form__menu" v-print="printObj"></el-button> -->
    <div class="render-form" id="printForm" ref="renderForm"  :style="{'min-height': formObj.canTodo ?  (isReturn ? 'calc(100vh - 100px)' : '550px'): ((formObj.code === 'drug_bill_personal' || formObj.code === 'drug_bill_cadre' || formObj.code === 'drug_bill_batch' || formObj.code === 'asset_bill_clear')) ? '630px' : 'calc(100vh - 100px)', width: (formObj.code === 'housing_bill_apply' || formObj.code === 'office_bill_apply') ? '950px' : '1160px', margin: '0 auto'}">
    <!-- <div class="render-form" id="printForm" ref="renderForm"  :style="{width: (formObj.code === 'housing_bill_apply' || formObj.code === 'office_bill_apply') ? '950px' : '1160px', margin: '0 auto'}"> -->
      <div v-if="formObj.formType != '2'">
        <!-- <div class="header" v-if="headerFlag" :style="{height: headerObj.height, background: headerObj.background}"> -->
        <div class="header" v-if="headerFlag" :style="{height: headerObj.height, background:'#E2E6ED'}">
          <div :style="{color: headerObj.styles.color, fontSize: headerObj.styles.fontSize, marginBottom: headerObj.styles.marginBottom, 'font-weight': 'bold'}">{{headerObj.value}}</div>
          <el-button type="text" icon="el-icon-printer" class="new-print-btn avue-form__menu" v-print="printObj">打印</el-button>
          <!-- <el-button type="primary" style="position:absolute;right: 10px;" icon="el-icon-printer" @click="printer">打印</el-button> -->
        </div>
        <avue-form ref="form"
            :defaults.sync="defaults"
            :option="newOption"
            v-model="form"
            @submit="handlePreviewSubmit">
            <template slot="menuForm">
              <el-select v-model="form.assignee"
                    v-if="showSelect"
                    class="manager-select"
                    multiple
                    :disabled="disableUser"
                    style="width: 220px !important;margin-right: 10px;float:left"
                    placeholder="请选择部门领导"
                    clearable>
                <el-option v-for="item in optionsUser"
                        :key="item.userId"
                        :label="item.realname"
                        :value="item.username">
                </el-option>
            </el-select>
             <el-button type="primary" v-if="item != '提交'" v-for="(item, index) in formObj.flagList" :key="index" @click="handlePreviewSubmit('', '', item)" :style="{'margin-left': item == '送审批' ? '70px': '10px'}">{{item}}</el-button>
              <!-- <el-button  icon="el-icon-delete" @click="close">关闭</el-button> -->
            </template>
        </avue-form>
      </div>
      <div v-else>
        <house-bill v-if="formObj.code === 'housing_bill_apply'" @printForm="printer" @getItemModal="getItemModal" :formObj="formObj" :detailObj="newformObj"></house-bill>
        <office-bill v-if="formObj.code === 'office_bill_apply'" @getItemModal="getItemModal" :formObj="formObj"></office-bill>
        <total-bill v-if="formObj.code === 'meeting_bill_apply'" @getItemModal="getItemModal" :formObj="formObj" :detailObj="newformObj"></total-bill>
      </div>
      <choose-member v-if="showChose" :labelkey="labelkey" :url1="url1" :url2="url2" :title="title" :columns1="columns1" :columns="columns" :limitLabel="limitLabel" :flKey="flKey" :type="type" :code="flowCode" :chosedKey="chosedKey" :choselist="choselist"></choose-member>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
import _ from 'lodash'
import eventBus from '@/util/eventBus'
import {getCurrentDate,getDiffDates} from '@/util/date'
import {getParentsNameById} from '@/util/util'
import { leaderAll, userSelectAll } from "@/api/admin/user";
import chooseMember from '@/components/chooseMember'
import {startProcess, billSubmit} from '@/api/bill'
import {mapGetters} from 'vuex'
import { setStore } from '@/util/store'
import { fetchTree } from '@/api/admin/sysarea'
import WidgetFormItem from '@/components/table-design/newFormItem'
import HouseBill from '@/components/house-bill'
import { fetchList as fetchList1 } from '@/api/asset/assetcategory'
import { fetchList as fetchList2 } from '@/api/asset/assetmodel'
import officeBill from '@/components/office-bill'
import totalBill from '@/components/total-bill'
import {getVisitingRoomOccupyInfo} from '@/api/visiting/oavisitingbill'
export default {
  components: { WidgetFormItem, HouseBill, officeBill, chooseMember, totalBill },
  props:['option', 'formObj', 'isReturn'],
  data () {
    return {
      form: {},
      newformObj: {},
      showSelect: false,
      optionsUser: [],
      disableUser: false,
      printObj: {
        id: "printForm",//打印区域 Dom ID
        popTitle: '打印页面标题文字',
        ignoreClass: 'avue-form__menu',
        // extraCss: 'https://www.google.com,https://www.google.com',
        // extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>,<style> #printForm { height: auto !important; } <style>'  ,//  可以传进去  style tag 标签；注意要逗号分隔   解决特定区域不显示问题；
      },
      defaults: {},
      optionsXh: [],
      flList: [],
      choselist:[],
      chosedKey: [],
      areaData: [],
      headerObj: {},
      headerFlag: false,
      newOption: {},
      showChose: false,
      edom: '',
      url1: '',
      url2: '',
      type: 'checkbox',
      limitLabel:'',
      columns:[],
      columns1:[],
      title: '',
      flKey: '',
      labelkey: '',
      flowCode:''
    }
  },
  computed: {
      ...mapGetters(['userInfo', 'tagList'])
  },
  created() {
    let _this = this
    this.init()
    this.listener()
    this.eventBusHandle()
    let content = this.formObj.content ? JSON.parse(this.formObj.content) : {}
    // if (this.formObj.code === 'card_bill_apply' || this.formObj.code === 'telephone_bill_apply' || this.formObj.code === 'telephone_bill_long' || this.formObj.code === 'officegoods_bill_apply' || this.formObj.code === 'telephone_bill_migrate' || this.formObj.code === 'drug_bill_batch' || this.formObj.code === 'car_bill_apply' || this.formObj.code === 'repair_bill_apply' || this.formObj.code === 'parking_bill_apply' || this.formObj.code === 'suggest_bill_apply' || this.formObj.code === 'meeting_bill_apply' || this.formObj.code === 'officespace_bill_apply' || this.formObj.code === 'corporate_bill_apply') {
    if (this.formObj.code !== 'drug_bill_personal' && this.formObj.code !== 'drug_bill_cadre' && this.formObj.code !== 'officegoods_bill_purchase' && this.formObj.code !== 'asset_bill_clear' && this.formObj.code !== 'asset_bill_handover' && this.formObj.code !== 'asset_bill_purchase' && this.formObj.code !== 'asset_bill_change' && this.formObj.code !== 'asset_bill_revert') {
      this.showSelect = true
      // leaderAll(this.userInfo.username).then(res => {
      userSelectAll('ROLE_DEPT_LEADER', this.userInfo.username).then(res => {
        this.optionsUser = res.data.data
      })
      if ((this.formObj.code === 'meeting_bill_apply' || this.formObj.code === 'housing_bill_apply') && this.formObj.taskName === '发起人') {
        let content = JSON.parse(this.formObj.content)
        this.newformObj = Object.assign({}, this.formObj)
        if (content.attachment){
          if(typeof(content.attachment) == 'string') {
            this.newformObj.attachment = JSON.parse(content.attachment)
          } else if(typeof(content.attachment) == 'object') {
            this.newformObj.attachment = content.attachment
          }
        }
        if (content.idCard) {
          this.newformObj.idCard = content.idCard
        }
        if (content.housing) {
          this.newformObj.housing = content.housing
        }
        if (content.parking) {
          this.newformObj.parking = content.parking
        }
        if (content.fileList1) {
          this.newformObj.fileList1 = content.fileList1
        }
        if (content.fileList2) {
          this.newformObj.fileList2 = content.fileList2
        }
        if (content.applyTimes && content.applyTimes.length) {
          this.newformObj.applyBeginTime = content.applyTimes[0] ? content.applyTimes[0] : ''
          this.newformObj.applyEndTime = content.applyTimes[1] ? content.applyTimes[1] : ''
      }
        if (content.billChecked) {
          this.newformObj.billChecked = content.billChecked
        }
      }
    }
    // }
    if (this.formObj.showSelectType && this.formObj.showSelectType.indexOf('ROLE_DEPT_LEADER') !== -1 || this.formObj.taskName === '发起人') {
      setTimeout(() => {
        let obj1 = {
          choselist: content.choselist,
          chosedKey: content.chosedKey,
        }
        if (content.drugList_choose_member) {
          obj1.drugList_choose_member = content.drugList_choose_member
        }
        if (content.officegoodsList_choose_member) {
          obj1.officegoodsList_choose_member = content.officegoodsList_choose_member
        }
        if (content.withMember_choose_member) {
          obj1.withMember_choose_member = content.withMember_choose_member
          obj1.withMember = content.withMember
        }
        eventBus.$emit('getMember', obj1)
        // eventBus.$emit('getMember', content)
      }, 500);
    }
    if (this.option && this.option.column && this.option.column.length > 0) {
      let column = []
      this.option.column.map(item => {
        // if (this.formObj.showSelectType && this.formObj.showSelectType.indexOf('ROLE_DEPT_LEADER') !== -1 || this.formObj.taskName === '发起人') {
        //   switch (item.prop) {
        //       case 'createName':
        //           content.createName = this.formObj.createName
        //           item.value = this.formObj.createName
        //           break
        //       case 'createPhone':
        //           content.createPhone = this.formObj.createPhone
        //           item.value = this.formObj.createPhone
        //           break
        //       case 'deptName':
        //           content.deptName = this.formObj.deptName
        //           item.value = this.formObj.deptName
        //           break
        //   }
        // }
        if (content[item.prop]) {
            item.value = content[item.prop]
        }
        if (item.prop === 'title') {
          item.value = this.formObj.title
        }
        if(item.prop === 'purchase_form' && !content['purchase_form']) {
          item.value = [{
          }]
        }
        if (item.prop === 'workTime' || item.prop === 'workPrice' || item.prop === 'consumablePrice' || item.prop === 'workTimePrice') {
          item.disabled = true
        }
         if (item.prop === 'remark' && (this.formObj.code === 'repair_bill_apply' || this.formObj.code === 'parking_bill_apply')) {
          item.disabled = true
        }
        if (item.type === 'header') {
          this.headerFlag = true
          this.headerObj = item
        } else {
          if (item.value && typeof(item.value) == 'string' && item.value.indexOf('$store') !== -1) {
            item.value = _.get(this, item.value)
          }
          if(item.height) {
            // 选药表格
            if (item.height === 'auto' &&  (item.prop === 'drugList_choose_member' || item.prop === 'officegoodsList_choose_member' || item.prop === 'assetList_choose_member')) {
              let styles = {
                height: item.height,
                'overflow': 'auto'
              }
              if (item.styles) {
                item.styles = Object.assign(item.styles, styles)
              } else {
                item.style = styles
              }
            } else if(item.height === '110px' && item.prop === 'purchase_form') {
              let styles = {
                height: item.height,
                'overflow': 'auto',
                'margin-left': '-50px'
              }
              if (item.styles) {
                item.styles = Object.assign(item.styles, styles)
              } else {
                item.style = styles
              }
            } else {
              let styles = {}
              if(item.prop === 'attachment') { // 意见建议上传按钮居上
                styles = {
                  height: item.height,
                  'align-items': 'center'
                }
              } else {
                styles = {
                  height: item.height,
                  'align-items': 'center',
                  'display': 'inline-flex',
                }
              }
              if (item.styles) {
                item.styles = Object.assign(item.styles, styles)
              } else {
                item.style = styles
              }
            }
          }
          if(item.prop === 'now') {
            if (this.formObj.code == 'car_bill_apply') {
              item.value = getCurrentDate('year')
            } else {
              item.value = getCurrentDate()
            }
          }
          if(item.prop === 'applyDate') {
            item.value = getCurrentDate('year')
          }
          column.push(item)
        }
        if (item.prop.indexOf('_choose_member') !== -1) {
          //this.formObj.code === 'visiting_bill_apply'||
          if (this.formObj.code === 'asset_bill_revert' || this.formObj.code === 'asset_bill_purchase' || this.formObj.code === 'asset_bill_handover' || this.formObj.code === 'asset_bill_requisition' || this.formObj.code === 'asset_bill_borrow') {
            if (this.formObj.code === 'asset_bill_handover' || item.prop === 'withMember_choose_member') {
              this.form[item.prop] = item.value
            } else {
              let astr = item.prop.replace('_choose_member', '')
              this.form[item.prop] = content[astr]
            }
          } else {
            this.form[item.prop] = item.value
          }
          
        }
        _this.formObj.commitList && this.formObj.commitList.map(citem => {
          if (citem.taskStatus === '1' && citem.taskName === item.prop) {
            item.value = '【' + citem.deptName + '-' + citem.realname + '】:' + (citem.message ? citem.message : '') + '。（' + citem.time + '）'
          }
        })
      })
      this.newOption = Object.assign({}, this.option)
      this.newOption.column = column
      this.newOption.emptyBtn = false
      // this.newOption.printBtn = true
      this.newOption.submitText = '提交'
      this.newOption.submitBtn = true
      setTimeout(() => {
        this.hoverClick()
      }, 100)
      
    }
  },
  watch:{
    'form.car_address':{
      handler(val){
        var field_address_other =this.findObject(this.option.column,'address_other')
        if (val === '其他') {
          field_address_other.display = true
        } else {
          field_address_other.display = false
        }
      }
    },
    'form.carType':{
      handler(val){
        var field_number =this.findObject(this.option.column,'number')
        var field_number_label =this.findObject(this.option.column,'number_label')
        if (val === '2') { //来访车辆
          field_number.display = true
          field_number_label.display = true
        } else {
          field_number.display = false
          field_number_label.display = false
        }
      }
    },
    /** 访客字段监控start*/
    'form.upstairFlag':{
      handler(val){
        //选择上楼时，主要领导的角色是ROLE_DEPT_MAIN_LEADER，不上楼部门领导还是ROLE_DEPT_LEADER
        if(val === '1'){
          userSelectAll('ROLE_DEPT_MAIN_LEADER', this.userInfo.username).then(res => {
            this.optionsUser = res.data.data
          })
        }else{
          userSelectAll('ROLE_DEPT_LEADER', this.userInfo.username).then(res => {
            this.optionsUser = res.data.data
          })
        }
       
      }
    },
    'form.parkFlag':{
      handler(val){
        //选择不停车的时候，取消车牌号必填
        if(val === '0'){
          if (this.newOption && this.newOption.column && this.newOption.column.length > 0) {
            this.newOption.column.forEach(item => {
              if (item.prop === 'carNo') {
                item.required = false
                item.rules[0].required = false
              }
            })
          }
        }
       if(val === '1'){
          if (this.newOption && this.newOption.column && this.newOption.column.length > 0) {
            this.newOption.column.forEach(item => {
              if (item.prop === 'carNo') {
                item.required = true
                item.rules[0].required = true
              }
            })
          }
        }
      }
    },
    /** 访客字段监控end*/
    'form.modelId':{
      handler(val){
        let modelForm = this.optionsXh.filter(item => {
            return item.modelId === val
        })
        if (modelForm.length > 0) {
          this.form.categoryId = modelForm[0].categoryId
          this.defaults.categoryId.disabled = true
          this.form.name = modelForm[0].name
          this.defaults.name.disabled = true
          this.form.spec = modelForm[0].spec
          this.defaults.spec.disabled = true
          this.form.unit = modelForm[0].unit
          this.defaults.unit.disabled = true
          this.form.price = modelForm[0].value
          this.form.cover = modelForm[0].cover
          this.form.timeLimit = this.flList.filter(item => {
              return item.categoryId === modelForm[0].categoryId
          })[0].timeLimit
        } else {
          this.form.categoryId = ''
          this.defaults.categoryId.disabled = false
          this.form.name = ''
          this.defaults.name.disabled = false
          this.form.unit = ''
          this.defaults.unit.disabled = false
          this.form.spec = ''
          this.defaults.spec.disabled = false
          this.form.price = undefined
          this.form.cover = ''
          this.form.timeLimit = undefined
        }
      }
    },
    
    /**'choselist':{
      handler(val){
        if (this.formObj.code == 'officegoods_bill_purchase'){
           //功能：深度监控办公用品采购申请的officegoodsList_choose_member或者choselist，动态填充采购预算

           //过滤填写了采购数量和单价的数据
          let handleList =  val.filter(item => {
            return item.preAmount&&item.price
          })
          //过滤属于《纸质文具及办公用品类》的数据
          let paperBudgetList =  handleList.filter(item => {
            return item.categoryParentId === 1
          })
          //过滤属于《硒鼓墨盒类》的数据
          let cartridgeBudgetList =  handleList.filter(item => {
            return item.categoryParentId === 2
          })
          //过滤属于《文教用品类》的数据
          let educationBudgetList =  handleList.filter(item => {
            return item.categoryParentId === 3
          })
          //过滤属于《其他办公消耗用品及类似物品》的数据
          let otherBudgetList =  handleList.filter(item => {
            return item.categoryParentId === 4
          })
          //按大类别计算采购预算总和
          let paperBudget = 0;
          let cartridgeBudget = 0;
          let educationBudget = 0;
          let otherBudget = 0;
          paperBudgetList?.forEach(oneItem =>{
            paperBudget = paperBudget + oneItem.preAmount*oneItem.price;
          })
          
          cartridgeBudgetList?.forEach(twoItem =>{
            cartridgeBudget = cartridgeBudget + twoItem.preAmount*twoItem.price;
          })
          
          educationBudgetList?.forEach(threeItem =>{
            educationBudget = educationBudget + threeItem.preAmount*threeItem.price;
          })
         
          otherBudgetList?.forEach(fourItem =>{
            otherBudget = otherBudget + fourItem.preAmount*fourItem.price;
          })
          this.form.purchase_form[0].paperBudget = paperBudget;
          this.form.purchase_form[0].cartridgeBudget = cartridgeBudget;
          this.form.purchase_form[0].educationBudget = educationBudget;
          this.form.purchase_form[0].otherBudget = otherBudget;
          //this.reloadKey++
          this.form.purchase_form[0].$index++
          console.log("paperBudget",paperBudget)
          console.log("cartridgeBudget",cartridgeBudget)
          console.log("educationBudget",educationBudget)
          console.log("otherBudget",otherBudget)
          console.log("this.form",this.form)
    }
  },
      deep:true,
      immediate:true
    }*/
  },
  methods: {
    hoverClick() {
      Array.from(document.getElementsByClassName('el-popover__reference')).forEach((v, index) =>{
        if (v.innerHTML === '药品名称【请选择(个人领药)+】' || v.innerHTML === '药品名称【请选择(批量领药)+】' || v.innerHTML === '药品名称【请选择(老干领药)+】' || v.innerHTML === '用品名称【请选择+】' || v.innerHTML === '采购用品名称【请选择+】' || v.innerHTML === '资产名称【请选择+】' || v.innerHTML === '维修资产【请选择+】' || v.innerHTML === '退库资产【请选择+】' || v.innerHTML === '借用资产【请选择+】' || v.innerHTML === '借用资产【请选择+】' || v.innerHTML === '清理资产【请选择+】' || v.innerHTML === '变更资产【请选择+】' || v.innerHTML === '变动资产【请选择+】' || v.innerHTML === '采购资产【请选择+】') {
          v.style.cursor = 'pointer'
          v.style.color = 'red'
        }
      })
    },
    listener() {
      let self = this
      document.addEventListener('click', function(e) {
        self.chosedKey = []
        //2023/05/21 设置弹窗的入口流程code
        self.flowCode = self.formObj.code
        // 表单选人
        let keyw = ''
        if ((e.target.className === 'el-input__inner' || e.target.className === 'el-input-group__append') && e.target.offsetParent && (e.target.offsetParent.attributes.title && e.target.offsetParent.attributes.title.value === '人员选择' && e.target.readOnly !== true || e.target.offsetParent.attributes.class && e.target.offsetParent.attributes.class.value.indexOf('chosemember') != -1 && e.target.readOnly !== true)  || (e.target.innerHTML === '选择' && e.target.offsetParent && e.target.offsetParent.className === 'el-input-group__append' && e.target.offsetParent.offsetParent && e.target.offsetParent.offsetParent.attributes.title && e.target.offsetParent.offsetParent.attributes.title.value === '人员选择') || (e.target.innerHTML === '选择' && e.target.offsetParent && e.target.offsetParent.className === 'el-input-group__append' && e.target.offsetParent.offsetParent && e.target.offsetParent.offsetParent.attributes.class && e.target.offsetParent.offsetParent.attributes.class.value.indexOf('chosemember') != -1)) {
          console.log("asdad222",e)
          /**  20230320前表单人员选择获取labelkey方式，页面一直获取不到e.path报错
          if (e.target.className) {
            self.labelkey = e.path[4].children[0].htmlFor
          } else {
            self.labelkey = e.path[5].children[0].htmlFor
          }
           */
          /**  
           * 20230320后表单人员通过流程code手工设置labelkey方式,对应页面手工选人业务需要单独设置
          */
         if(self.formObj.code === 'asset_bill_handover'|| self.formObj.code === 'asset_bill_change'||self.formObj.code === 'car_bill_apply'||self.formObj.code ==='visiting_bill_apply'){
           self.labelkey ='withMember_choose_member'
         }
         if (self.formObj.code === 'asset_bill_handover' || self.formObj.code === 'asset_bill_change'||self.formObj.code ==='visiting_bill_apply') {
            self.type = 'radio'
          }

          if (self.formObj.code === 'asset_bill_handover' || self.formObj.code === 'asset_bill_change'||self.formObj.code ==='visiting_bill_apply') {
            self.type = 'radio'
          } else {
            self.type = 'checkbox'
          }
          self.showChose = true
          self.url1 = '/admin/dept/tree'
          keyw = 'userId'
          self.url2 = '/admin/user/page/simple'
          self.title = '组织机构'
          self.flKey = 'deptId'
          self.columns = [
            {
                title: '用户名',
                dataIndex: 'username',
                key: 'username',
            },
            {
                title: '姓名',
                key: 'realname',
                dataIndex: 'realname',
            },
            {
                title: '所属部门',
                dataIndex: 'deptId',
                key:'deptId',
                scopedSlots: { customRender: 'deptId' },
            },
            {
                title: '岗位',
                dataIndex: 'post',
                key: 'post',
                scopedSlots: { customRender: 'post' }
            }
          ]
          self.columns1 = [
            {
                title: '姓名',
                dataIndex: 'realname',
                key: 'realname' 
            },
            // {
            //     title: '操作',
            //     key: 'action',
            //     scopedSlots: { customRender: 'action' },
            // },
          ]
        }
        // 表单选药
        if(e.target.innerHTML === '药品名称【请选择(个人领药)+】' || e.target.innerHTML === '药品名称【请选择(批量领药)+】' || e.target.innerHTML === '药品名称【请选择(老干领药)+】') {
          self.labelkey = 'drugList_choose_member'
          self.showChose = true
          self.url1 = '/act/drugcategory/tree'
          // self.url2 = '/act/drug/page'
          self.url2 = '/act/drugstock/page'
          self.title = '药品类别'
          self.limitLabel = e.target.innerHTML
          self.columns = [
            {
                title: '药品名',
                dataIndex: 'name',
                key: 'name',
                width: 150
            },
            // {
            //     title: '简称',
            //     key: 'pinyin',
            //     width: 100,
            //     dataIndex: 'pinyin',
            // },
            // {
            //     title: '药品单位',
            //     key: 'unit',
            //     width:100,
            //     align: 'center',
            //     dataIndex: 'unit',
            // },
            {
                title: '适应症',
                dataIndex: 'indications',
                key:'indications'
            },
            {
                title: '注意事项',
                dataIndex: 'attention',
                key: 'attention',
            }
          ]
          self.flKey = 'categoryId'
          self.columns1 = [
            {
                title: '药品名',
                dataIndex: 'name',
                key: 'name' 
            },
            // {
            //     title: '操作',
            //     key: 'action',
            //     scopedSlots: { customRender: 'action' },
            // },
          ]
          keyw = 'drugId'
        }
        // 办公用品申请 办公用品采购申请
        if(e.target.innerHTML === '用品名称【请选择+】' || e.target.innerHTML === '采购用品名称【请选择+】') {
          self.labelkey = 'officegoodsList_choose_member'
          self.showChose = true
          self.url1 = '/act/officegoodscategory/tree'
          self.url2 = '/act/officegoodsstock/page'
          self.title = '用品类别'
          keyw = 'officegoodsId'
          self.limitLabel = e.target.innerHTML
          self.columns = [
            {
              title: "序号",
              width: 30,
              align: 'center',
              customRender: (text, record, index) => `${index + 1}`,
            },
            {
                title: '用品名',
                dataIndex: 'name',
                key: 'name',
                width: 150
            },
             {
                title: '图片',
                key: 'cover',
                width: 100,
                scopedSlots: { customRender: 'cover' },
                dataIndex: 'cover',
            }
          ]
          self.flKey = 'categoryId'
          self.columns1 = [
            {
                title: '用品名',
                dataIndex: 'name',
                key: 'name' 
            },
            // {
            //     title: '操作',
            //     key: 'action',
            //     scopedSlots: { customRender: 'action' },
            // },
          ]
        }
        // 维修申请
        if(e.target.innerHTML === '维修资产【请选择+】' || e.target.innerHTML === '资产名称【请选择+】' || e.target.innerHTML === '退库资产【请选择+】' || e.target.innerHTML === '借用资产【请选择+】' || e.target.innerHTML === '清理资产【请选择+】' || e.target.innerHTML === '变更资产【请选择+】' || e.target.innerHTML === '变动资产【请选择+】' || e.target.innerHTML === '采购资产【请选择+】') {
          self.labelkey = 'assetList_choose_member'
          self.showChose = true
          self.url1 = '/act/assetcategory/tree?status=1'
          self.url2 = '/act/asset/page'
          self.title = '资产类别'
          keyw = 'assetId'
          self.limitLabel = e.target.innerHTML
          self.columns = [
            {
                title: '资产名',
                dataIndex: 'name',
                key: 'name',
                width: 150
            },
            {
                title: '规格',
                key: 'spec',
                width: 80,
                dataIndex: 'spec',
            },
            {
                title: '单位',
                key: 'unit',
                width: 80,
                dataIndex: 'unit',
            },
            // {
            //     title: '编号',
            //     key: 'no',
            //     width: 100,
            //     dataIndex: 'no',
            // },
            // {
            //     title: 'sn',
            //     key: 'sn',
            //     width: 80,
            //     dataIndex: 'sn',
            // },
            // {
            //     title: '品牌',
            //     key: 'brand',
            //     width: 80,
            //     dataIndex: 'brand',
            // },
            // {
            //     title: '地址',
            //     key: 'address',
            //     width: 150,
            //     dataIndex: 'address',
            // },
            {
                title: '图片',
                key: 'cover',
                width: 100,
                scopedSlots: { customRender: 'cover' },
                dataIndex: 'cover',
            }
          ]
          self.flKey = 'categoryId'
          self.columns1 = [
            {
                title: '资产名',
                dataIndex: 'name',
                key: 'name' 
            },
            // {
            //     title: '操作',
            //     key: 'action',
            //     scopedSlots: { customRender: 'action' },
            // },
          ]
        }
        if (typeof(self.form[self.labelkey]) == 'object') {
            self.form[self.labelkey] && self.form[self.labelkey].map(item => {
              self.chosedKey.push(item[keyw])
            })
            self.choselist = self.form[self.labelkey]
        } else if (typeof(self.form[self.labelkey]) == 'string') {
          self.choselist.map(item => {
            self.chosedKey.push(item[keyw])
          })
        }
      })
    },
    init() {
      fetchTree().then(response => {
        this.areaData = response.data.data
      })
      fetchList1({current: 1, size:1000}).then(response => {
          this.flList = response.data.data.records
      })
      fetchList2({
          current: 1,
          size:1000,
          status: '1'
      }).then(response => {
          this.optionsXh = response.data.data.records
      })
    },
    printer() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      setTimeout(() => {
        loading.close();
        this.$print(this.$refs.renderForm);
      }, 2000);
    },
    getItemModal() {
      this.close()
    },
    eventBusHandle () {
      let _this = this
      eventBus.$on('getMember', function (data) {
        _this.chosedKey = data.chosedKey
        _this.choselist = data.choselist
        _this.form = Object.assign(_this.form, data)

        //业务场景处理 访客申请界面 根据被访选择自动填充业务字段，withMember为表单管理里面设置的值前缀
        if(_this.formObj.code==='visiting_bill_apply'){
          _this.form.visitDeptName = data['withMember'][0].deptName
          _this.form.visitUserPhone = data['withMember'][0].phone
        }
        
        _this.$nextTick(() => {
          _this.newOption.column && _this.newOption.column.map(item => {
            if ((item.prop === 'drugList_choose_member' || item.prop === 'officegoodsList_choose_member') && item.children && item.children.column.length > 0) {
              let a = -1
              Array.from(document.getElementsByClassName('el-input__inner')).forEach((v, index) =>{
                  if (v.getAttribute('aria-valuemax') === 'Infinity' && v.placeholder === '请输入 数量') {
                    a++
                    if (data[item.prop][a]) {
                      v.max = data[item.prop][a].limitAmount ? data[item.prop][a].limitAmount : 100000000
                      if (_this.formObj.code == 'officegoods_bill_apply') {
                        v.setAttribute('data-count', data[item.prop][a].stockAmount)
                      } else {
                        v.setAttribute('data-count', data[item.prop][a].amount)
                      }
                    }
                  }
                  if (_this.formObj.code != 'drug_bill_batch') {
                    if (_this.formObj.code == 'officegoods_bill_apply' || _this.formObj.code == 'drug_bill_personal' || _this.formObj.code == 'drug_bill_cadre') {
                      v.oninput = function(e) {
                        if (!isNaN(Number(v.value)) && e.target.getAttribute('aria-label') === '请输入 数量') {
                          if (v.getAttribute('data-count') == 0 || Number(v.value) > v.getAttribute('data-count')) {
                            _this.$message.error('库存不足')
                            v.value= ''
                          } else if (Number(v.value) > v.max) {
                            _this.$message.error('请不要超过限额数量')
                            v.value = v.max
                          }
                        }
                      }
                    } else {
                      v.oninput = function(e) {
                        if (!isNaN(Number(v.value)) && e.target.getAttribute('aria-label') === '请输入 数量') {
                          if (Number(v.value) > v.max) {
                            _this.$message.error('请不要超过限额数量')
                            v.value = v.max
                          }
                        }
                      }
                    }
                  }
              })
            }
          })
        })
      })
    },
    handlePreviewSubmit(from, done, type) {
      let formDta = Object.assign(this.formObj)
      formDta.bizData = this.form
      let countFlag = true
      let ysflag = true
      if(type) {
         this.$confirm('确定提交此处理?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let params = { 
              'billId': formDta.billId,
              'comment': '',
              'flag': type,
              'taskId': formDta.taskId
            }
            formDta.bizData.officegoodsList = formDta.bizData.officegoodsList_choose_member
            params.bizData = formDta.bizData
            params.assignee = formDta.assignee
            billSubmit(params).then(response => {
              this.$message.success('处理成功')
              this.$router.go(-1)
            })
          })
      } else {
        if (formDta.code === 'drug_bill_personal' || formDta.code === 'drug_bill_batch' || formDta.code === 'drug_bill_cadre') {
          if (formDta.code === 'drug_bill_personal') {
            formDta.bizData.applyType = '1'
          } else if(formDta.code === 'drug_bill_batch') {
            formDta.bizData.applyType = '2'
          } else {
            formDta.bizData.applyType = '3'
          }
          let drugList = []
          let chosedKey = []
          if (!formDta.bizData.drugList_choose_member || formDta.bizData.drugList_choose_member.length === 0) {
            this.$message.error('请选择药品领用清单')
            done()
            return
          } else {
            formDta.bizData.drugList_choose_member.map(item => {
              // item.drugId = item.drugId
              if (!item.preAmount && countFlag) {
                countFlag = false
                this.$message.error('请填写药品领用数量')
                done()
              }
              drugList.push(item)
              chosedKey.push(item.drugId)
            })
            formDta.bizData.drugList = formDta.bizData.drugList_choose_member = formDta.bizData.choselist = drugList
            formDta.bizData.chosedKey = chosedKey
          }
        } else if(formDta.code === 'car_bill_apply') {
          formDta.bizData.useTimes = [];
          if (this.form.car_address === '其他' && !this.form.address_other) {
            this.$message.error('请填写其他出车地点')
            done()
            return
          } else if(this.form.car_address !== '其他') {
            formDta.bizData.address = this.form.car_address
          } else {
            formDta.bizData.address = this.form.address_other
          }
          if (new Date(formDta.bizData.startTime).getTime() >= new Date(formDta.bizData.endTime).getTime()) {
            this.$message.error('开始时间应该小于结束时间')
            done()
            return
          }
          if (Object.prototype.hasOwnProperty.call(this.form,'startTime')) {
            formDta.bizData.useTimes.push(formDta.bizData.startTime);
          }
          if (Object.prototype.hasOwnProperty.call(this.form,'endTime')) {
            formDta.bizData.useTimes.push(formDta.bizData.endTime);
          }
        } else if(formDta.code === 'construction_bill'){
          if (new Date(formDta.bizData.startTime).getTime() > new Date(formDta.bizData.endTime).getTime()) {
            this.$message.error('开始时间应该小于结束时间')
            done()
            return
          }
        }else if (formDta.code === 'officegoods_bill_apply' || formDta.code === 'officegoods_bill_purchase') {
          let officegoodsList = []
          if (!formDta.bizData.officegoodsList_choose_member || formDta.bizData.officegoodsList_choose_member.length === 0) {
            this.$message.error('请选择物品清单')
            done()
            return
          } else {
            formDta.bizData.officegoodsList_choose_member.map(item => {
              if (!item.preAmount && countFlag) {
                countFlag = false
                this.$message.error('请填写物品数量')
                done()
              }
              officegoodsList.push(item)
            })
            formDta.bizData.officegoodsList = officegoodsList
          }
          
          if (formDta.bizData.purchase_form && formDta.bizData.purchase_form.length === 1) {
            formDta.bizData.purchase_form.map(vitem => {
              if (!vitem.paperBudget && vitem.paperBudget !== 0 && ysflag && countFlag) {
                this.$message.error('请填写纸质文具及办公用品类预算')
                ysflag = false
                done()
                return
              } else if (!vitem.cartridgeBudget && vitem.cartridgeBudget !== 0 && ysflag && countFlag) {
                this.$message.error('请填写硒鼓墨盒类预算')
                ysflag = false
                done()
                return
              } else if (!vitem.otherBudget && vitem.otherBudget !== 0 && ysflag && countFlag) {
                this.$message.error('请填写其他办公用品及消耗用品类预算')
                ysflag = false
                done()
                return
              } else if (!vitem.educationBudget && vitem.educationBudget !== 0 && ysflag && countFlag) {
                this.$message.error('请填写文教用品类预算')
                ysflag = false
                done()
                return
              }
            })
            if(ysflag) {
              formDta.bizData.paperBudget =  formDta.bizData.purchase_form.paperBudget
              formDta.bizData.cartridgeBudget =  formDta.bizData.purchase_form.cartridgeBudget
              formDta.bizData.otherBudget =  formDta.bizData.purchase_form.otherBudget
              formDta.bizData.educationBudget =  formDta.bizData.purchase_form.educationBudget
            }
          }
        } else if (formDta.code === 'asset_bill_requisition' || formDta.code === 'asset_bill_revert' || formDta.code === 'asset_bill_borrow' || formDta.code === 'asset_bill_clear' || formDta.code === 'asset_bill_change' || formDta.code === 'asset_bill_handover' || formDta.code === 'asset_bill_purchase') {
          if (!formDta.bizData.assetList_choose_member || formDta.bizData.assetList_choose_member.length === 0) {
            this.$message.error('请选择资产清单')
            done()
            return
          } else {
            
            if (formDta.code === 'asset_bill_purchase') {
                formDta.bizData.assetList_choose_member.map(item => {
                  if (!item.amount && countFlag) {
                    countFlag = false
                    this.$message.error('请填写资产数量')
                    done()
                  }
                })
            }
            formDta.bizData.assetList = formDta.bizData.assetList_choose_member
          }
          if (formDta.code === 'asset_bill_change') {
            if (formDta.bizData.withMember && formDta.bizData.withMember.length) {
              formDta.bizData.useId = formDta.bizData.withMember[0].userId
              formDta.bizData.useName = formDta.bizData.withMember[0].username
              formDta.bizData.useRealname = formDta.bizData.withMember[0].realname
              formDta.bizData.useDeptId = formDta.bizData.withMember[0].deptId
              formDta.bizData.useDeptName = formDta.bizData.withMember[0].deptName
            }
            if (!formDta.bizData.categoryId && !formDta.bizData.modelId && !formDta.bizData.name && !formDta.bizData.spec && !formDta.bizData.unit && !formDta.bizData.source && !formDta.bizData.price && !formDta.bizData.areaId && !formDta.bizData.useId && !formDta.bizData.address && !formDta.bizData.buyDate && !formDta.bizData.cover) {
              this.$message.error('资产类别、资产名称、规格、型号、计量单位、购入日期、区域、存放地点、使用期限、来源、照片 至少填一项不能为空')
              done()
              return
            }
          }
          if (formDta.code === 'asset_bill_handover') {
            if (formDta.bizData.withMember && formDta.bizData.withMember.length) {
              formDta.bizData.targetId = formDta.bizData.withMember[0].userId
              formDta.bizData.targetName = formDta.bizData.withMember[0].username
              formDta.bizData.targetRealname = formDta.bizData.withMember[0].realname
              formDta.bizData.targetDeptId = formDta.bizData.withMember[0].deptId
              formDta.bizData.targetDeptName = formDta.bizData.withMember[0].deptName
              formDta.assignee = formDta.bizData.withMember[0].username
            }
            if (!formDta.bizData.targetId) {
              this.$message.error('请选择变动人员')
              done()
              return
            }
          }
        } else if (formDta.code === 'visiting_bill_apply') {
          
            if (formDta.bizData.withMember && formDta.bizData.withMember.length) {
              formDta.bizData.visitUserId = formDta.bizData.withMember[0].userId
              formDta.bizData.visitUsername = formDta.bizData.withMember[0].realname
              //formDta.bizData.visitRealname = formDta.bizData.withMember[0].realname
              formDta.bizData.visitUserPhone = formDta.bizData.withMember[0].phone
              formDta.bizData.visitDeptId = formDta.bizData.withMember[0].deptId
              formDta.bizData.visitDeptName = formDta.bizData.withMember[0].deptName
            }else{
              formDta.bizData.visitUserId = this.$store.getters.userInfo.userId
              formDta.bizData.visitUsername = this.$store.getters.userInfo.realname
              //formDta.bizData.visitRealname = this.$store.getters.userInfo.realname
              formDta.bizData.visitUserPhone = this.$store.getters.userInfo.phone
              formDta.bizData.visitDeptId = this.$store.getters.userInfo.deptId
              formDta.bizData.visitDeptName = this.$store.getters.userInfo.deptName
            }



            //当来访日期、开始时间、结束时间、接待室不为空时，判断接待室是否空闲
            /**if(formDta.bizData.appointmentDate&&formDta.bizData.startTime&&formDta.bizData.endTime&&formDta.bizData.downstairRoomNo){
              getVisitingRoomOccupyInfo({
                appointmentDate:formDta.bizData.appointmentDate,
                startTime:formDta.bizData.startTime,
                endTime:formDta.bizData.endTime,
                downstairRoomNo:formDta.bizData.downstairRoomNo
              }).then(res => {
                if(res.data.data?.length>0){
                  //排除掉本流程的预约时间
                  let visitingRoomList = res.data.data
                  let bizIds = visitingRoomList.filter(item=>{item.bizId!==formDta.bizData.bizId})
                  console.log("bizIds",bizIds)
                  if(bizIds.length>0){
                    this.$message.error('当前接待室在来访申请的时间段已被预约!')
                    done()
                    return
                  }
                }
              })
            }*/
            //判断结束时间必须大于开始时间
            if(formDta.bizData.startTime&&formDta.bizData.endTime){
              var startTime = new Date(formDta.bizData.startTime).getDate()
              formDta.bizData.appointmentDate = startTime//预设值，默认来访日期为开始时间
              let dayDiff = getDiffDates(formDta.bizData.startTime,formDta.bizData.endTime)
              
              if(dayDiff<0){
                this.$message.error('来访结束时间必须晚于开始时间!')
                done()
                return
              }
              if(dayDiff>3){
                this.$message.error('来访结束时间和开始时间间隔最多不能超过3天!')
                done()
                return
              }
            }
          }
        // if (formDta.code === 'card_bill_apply' || formDta.code === 'telephone_bill_apply' || formDta.code === 'telephone_bill_long' || formDta.code === 'officegoods_bill_apply' || formDta.code === 'telephone_bill_migrate' || formDta.code === 'drug_bill_batch' || formDta.code === 'car_bill_apply' || formDta.code === 'repair_bill_apply' || formDta.code === 'parking_bill_apply' || formDta.code === 'suggest_bill_apply' || formDta.code === 'officespace_bill_apply' || formDta.code === 'corporate_bill_apply') {
        // if (formDta.code !== 'drug_bill_personal' && countFlag && formDta.code !== 'drug_bill_cadre') {
        if (formDta.code !== 'drug_bill_personal' && formDta.code !== 'drug_bill_cadre' && formDta.code !== 'officegoods_bill_purchase' && formDta.code !== 'asset_bill_clear' && formDta.code !== 'asset_bill_handover' && formDta.code !== 'asset_bill_purchase' && formDta.code !== 'asset_bill_change' && formDta.code !== 'asset_bill_revert' && countFlag) {  
        // if (formDta.code !== 'drug_bill_personal' && countFlag) {
          if (!this.form.assignee || this.form.assignee.length === 0) {
            this.$message.error('请选择部门领导')
            done()
            return
          } else {
            formDta.assignee = this.form.assignee.join()
          }
        }
        // }
        if (formDta.bizData.areaId) {
          let list = getParentsNameById(formDta.bizData.areaId, this.areaData)
          formDta.bizData.areaName = list.join('')
        }
        if (formDta.bizData.migrateAreaId) {
          let list = getParentsNameById(formDta.bizData.migrateAreaId, this.areaData)
          formDta.bizData.migrateAreaName = list.join('')
        }
        if(countFlag && ysflag) {
          this.$confirm('确定提交?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (formDta.showSelectType && formDta.showSelectType.indexOf('ROLE_DEPT_LEADER') !== -1 || formDta.taskName === '发起人') {
              let params = { 
                'billId': formDta.billId,
                'comment': '',
                'flag': '提交',
                'taskId': formDta.taskId
              }
              params.bizData = formDta.bizData
              params.assignee = formDta.assignee
              billSubmit(params).then(response => {
                this.$message.success('处理成功')
                // let list = this.tagList.filter(item => {
                //   return item.value !== '/approvaltask/index'
                // })
                // setStore({ name: 'tagList', content: list, type: 'session' })
                // let tag = this.tagList.filter(item => {
                //     return item.value.indexOf('/db/detail') !== -1
                // })
                // if (tag.length > 0) {
                //     this.$router.$avueRouter.closeTag(tag[0])
                // }
                // this.$router.push({
                //   path: '/approvaltask/index'
                // })
                this.$router.go(-1)
              })
            } else {
              startProcess(formDta).then(response => {
                if (formDta.code === 'drug_bill_personal' || formDta.code === 'drug_bill_batch' || formDta.code === 'drug_bill_cadre') {
                  this.$message.success('提交成功,申请单一周失效，请及时领取')
                } else {
                  this.$message.success('提交成功')
                }
                this.close()
              }).catch(() => {
                // this.$message.error('提交失败')
                // this.close()
                done()
              })
            }
          }).catch(() => {
            done()
          });
        }
      }
    },
    close() {
      this.$emit('getModal', false)
    }
  }
}
</script>

<style lang="scss">
.new-render-wrapper{
  position: relative;
  .new-print-btn{
    // position: absolute;
    // top: -20px;
    // left: 20px;
  }
}
@media print {
    #printForm{
        height: auto !important;
        padding-bottom: 2px;
        padding-right: 2px;
    }
    body {margin-top: 10mm; margin-bottom: 10mm; 
           margin-left: 5mm; margin-right: 5mm}
}
@page {
    margin: 8mm 2mm;
 }
 input::placeholder, textarea::placeholder  {
  font-size: 12px;  // 更改字体大小
}

input::-webkit-input-placeholder, textarea::placeholder { /* WebKit browsers */ 
  font-size:12px;
}
input:-moz-placeholder, textarea::placeholder { /* Mozilla Firefox 4 to 18 */ 
  font-size:12px;
}
input::-moz-placeholder, textarea::placeholder { /* Mozilla Firefox 19+ */
  font-size:12px;
}
input:-ms-input-placeholder, textarea::placeholder { /* Internet Explorer 10+ */
  font-size:12px;
} 
</style>
